package com.itstyle.quartz.handler;

import net.minidev.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 张霄峰
 * @email 29839415@qq.com
 * @date 2020/4/15 12:02
 */
@Component
public class ApiInterceptor implements HandlerInterceptor {

    //请求前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
        if (httpServletRequest.getMethod().equals("OPTIONS")){//处理预请求
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        HttpSession session = httpServletRequest.getSession();
        if(session.getAttribute("user") != null) {
            return true;
        }else {
            Map<String, Object> object = new ConcurrentHashMap<String, Object>();
            object.put("msg","请重新登录");
            String jsonObjectStr = JSONObject.toJSONString(object);
            InterceptUtil.returnJson(httpServletResponse,jsonObjectStr);
            return false;
        }
    }

    //请求时
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
    }

    //请求完成
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");// 解决IFrame拒绝的问题
    }
}
